package com.demo.alipay.study.controller;


import com.alibaba.fastjson.JSONObject;
import com.demo.alipay.study.config.AlipayConfig;
import com.demo.alipay.study.service.AlipayService;
import com.demo.alipay.study.service.pay.PayCommonService;
import com.demo.alipay.study.vo.PayVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: lvfeilong
 */
@Controller
@Log4j2
public class AlipayController {

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private PayCommonService payCommonService;

    @Autowired
    private AlipayConfig alipayConfig;

    private static final String PRODUCT_COURSE = "productcourse";
    private static final String S_VIP = "svip";
    private static final String AWARD = "award";

    /**
     * 支付宝支付生成二维码
     *
     * @param courseid 课程id
     * @return 二维码
     */
    @GetMapping("/alipay/pay")
    @ResponseBody
    public byte[] aliPay(String courseid) {
        PayVo payVo = new PayVo();
        payVo.setCourseid(courseid);
        payVo.setUserId("1");
        return alipayService.aliPay(payVo);
    }

    /**
     * 定义支付回调的地址
     * <p>
     * 1：第一步：打成一个jar 发布正式服务器
     * 2：第二步：购买一个域名：https:/www.kuangstudy.com/
     * 3：第三步：部署的项目到服务器上。java -jar ksd-alipay.jar >>1.txt &
     * 4：第四步：获取真实的回调地址  https:/www.kuangstudy.com/alipay/notifyUrl?body=&param&
     */
    @ResponseBody
    @RequestMapping("/alipay/notifyUrl")
    public String notifyUrl(HttpServletRequest request) {
        // 1: 调用支付回调
        boolean result = aliPayCallBack(request);
        if (result) {
            // 请不要修改或删除
            return "success";
        } else {
            // 验证失败
            return "fail";
        }
    }


    /**
     * 支付宝支付回调
     *
     * @param request 请求
     * @return 回调结果
     */
    private boolean aliPayCallBack(HttpServletRequest request) {
        // 1:获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<>(16);
        Map<String, String[]> requestParams = request.getParameterMap();
        //获取回传请求参数还原参数值
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
        }
        //2：计算得出通知验证结果
        log.info("1：---->获取支付宝回传的参数---------------------------------->" + params);
        // 返回公共参数
        String tradeNo = params.get("trade_no");
        //支付返回的请求参数body
        String bodyJson = params.get("body");
        log.info("3---->:【支付宝】交易的参数信息是：{}，流水号是：{}", bodyJson, tradeNo);
        try {
            JSONObject bodyJsonObject = JSONObject.parseObject(bodyJson);
            String userId = bodyJsonObject.getString("userId");
            String ptype = bodyJsonObject.getString("ptype");
            String orderNumber = bodyJsonObject.getString("orderNumber");
            log.info("4---->:【支付宝】交易的参数信息是：ptype:{}，orderNumber是：{}", ptype, orderNumber);
            // 课程支付成功，保存的订单交易明细
            if (PRODUCT_COURSE.equalsIgnoreCase(ptype)) {
                payCommonService.payProductCourse(bodyJsonObject, "1", orderNumber, tradeNo, "1");
            }
            if (S_VIP.equalsIgnoreCase(ptype)) {
                payCommonService.payUserSVip(bodyJsonObject, "1", orderNumber, tradeNo, "1");
            }
            if (AWARD.equalsIgnoreCase(ptype)) {
                payCommonService.awardPay(bodyJsonObject, "1", orderNumber, tradeNo, "1");
            }
        } catch (Exception ex) {
            log.info("支付宝支付出现了异常.....");
            ex.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 获取支付宝支付配置信息
     *
     * @return 配置信息
     */
    @GetMapping("/config")
    @ResponseBody
    public String config() {
        return alipayConfig.toString();
    }
}
